#ifndef THREAD_POOL_H
#define THREAD_POOL_H

#include <memory>

class ThreadPoolData;
class Runnable;
/**
 * thread pool
 *
 * @author: haitao.lin
 */
//TODO: 运行过程中动态扩展/收缩线程数
class ThreadPool
{
public:
  explicit ThreadPool();
  virtual ~ThreadPool();

  /**
   * Reserves a thread and uses it to run runnable, unless this thread will make the current thread count exceed maxThreadCount().
   * In that case, runnable is added to a run queue instead.
   * The priority argument can be used to control the run queue's order of execution.
   *
   * Note that the thread pool takes ownership of the runnable if runnable->autoDelete() returns true,
   * and the runnable will be deleted automatically by the thread pool after the runnable->run() returns.
   * If runnable->autoDelete() returns false, ownership of runnable remains with the caller.
   * Note that changing the auto-deletion on runnable after calling this functions results in undefined behavior.
   */
  void start(Runnable *runnable, int priority = 0);

  /**
   * Removes the runnables that are not yet started from the queue.
   * The runnables for which runnable->autoDelete() returns true are deleted
   */
  void clear();

  /**
   * This property represents the maximum number of threads used by the thread pool.
   */
  void setMaxThreadCount(int max_thread_count);
  int maxThreadCount();

  /**
   * Waits up to msecs milliseconds for all threads to exit and removes all threads from the thread pool.
   * Returns true if all threads were removed; otherwise it returns false.
   * If msecs is -1 (the default), the timeout is ignored (waits for the last thread to exit)
   */
  bool waitForDone(int msecs = -1);

private:
  std::unique_ptr<ThreadPoolData> data_;
};

#endif //THREAD_POOL_H
